import React, { Component } from 'react';

import FormInput from '../../core/components/form.input';
import FormSelect from '../../core/components/form.select';
import FormDate from '../../core/components/form.date';
import { Get, Post, PostString } from '../../core/utils/fetch';
import Dialog from '../../core/utils/dialog';
import Header from '../../core/components/header';
import Moment from 'moment';

const idMatch = /id=(\d+)/
const onlyMatch = /only=true/
const auditMatch = /audit=true/

let startDate = null,
    endDate = null,
    productId = null,
    car = null;

class InvestmentEdit extends Component {

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    id = ""

    constructor(props) {
        super(props);
        let m = idMatch.exec(props.location.search);
        if (m) {
            this.id = m[1];
        }
        let o = onlyMatch.exec(props.location.search);
        let c = auditMatch.exec(props.location.search);
        if (o || c) {
            if (c) {
                this.audit = true;
            }
            this.only = true;
        } else {
            this.only = false;
        }
    }

    state = {
        investmentData: {},
    };

    componentDidMount = () => {
        this._refresh();
    };

    render() {
        let { investmentData } = this.state;
        investmentData.productId = investmentData.productId || {};
        investmentData.car = investmentData.car || {};
        return (
            <div>
                <Header title="投资用户" subTitle="Money Manage"></Header>
                <div className="row">
                    <div className="col-lg-4">
                        <div>
                            <form role="form">
                                <FormInput disabled={this.only} className="has-success" label="姓名*" name="custName" dataItem={investmentData}></FormInput>
                                <FormInput disabled={this.only} className="has-success" label="联系方式*" name="custPhone" dataItem={investmentData}></FormInput>
                                <FormSelect disabled={this.only} className="has-error" label="投资产品*" dataItem={investmentData.productId} 
                                    onChange={(value) => {
                                        productId = value
                                    }} name="id" dataUrl="/spi/product/list"></FormSelect>
                                <FormInput disabled={this.only} className="has-success" label="投资金额(元)" name="investNum" dataItem={investmentData} onChange={this._calc}></FormInput>
                                <FormInput disabled={this.only} className="has-success" label="年化收益率(%)" extra={<label>只需要输入数字，不需要输入%</label>} name="rate" dataItem={investmentData} onChange={this._calc}></FormInput>
                                <FormInput disabled={this.only} className="has-success" label="投资周期(月)" name="period" dataItem={investmentData} onChange={this._calc}></FormInput>
                                <FormInput disabled={this.only} className="has-success" readOnly={true} label="到期收益" name="expectedReturn" dataItem={investmentData}></FormInput>
                                <FormDate disabled={this.only} className="has-success" label="认购日期" name="beginDate" dataItem={investmentData}
                                    onChange={(value) => {
                                        startDate = value
                                    }}></FormDate>
                                <FormDate disabled={this.only} className="has-success" label="回购日期" name="endDate" dataItem={investmentData}
                                    onChange={(value) => {
                                        endDate = value
                                    }}></FormDate>
                                <FormSelect disabled={this.only} className="has-success" label="车辆信息" dataItem={investmentData.car}
                                    onChange={(value) => {
                                        car = value
                                    }} name="id" dataUrl="/spi/custInvest/findCars" dataHandler={this._dataHandler}></FormSelect>
                            </form>
                        </div>

                        <div className="color-green">
                            带*为必填项
                        </div>
                        {this.renderButtons()}
                    </div>
                </div>
            </div>
        );
    }

    renderButtons = () => {
        if (this.only && !this.audit) {
            return (
                <button type="button" className="btn btn-sm btn-primary" style={{ "marginRight": "10px" }} onClick={this._back}>返回</button>
            )
        }
        else if (this.audit) {
            return (
                <div>
                    <button type="button" className="btn btn-sm btn-primary" style={{ "marginRight": "10px" }} onClick={() => this._audit('pass')}>审核通过</button>
                    <button type="button" className="btn btn-sm btn-danger" style={{ "marginRight": "10px" }} onClick={() => this._audit('reject')}>审核不通过</button>
                    <button type="button" className="btn btn-sm btn-primary" style={{ "marginRight": "10px" }} onClick={this._back}>返回</button>
                </div>
            )
        } else {
            return (
                <div>
                    <button type="button" className="btn btn-sm btn-primary" style={{ "marginRight": "10px" }} onClick={this._save}>保存</button>
                    <button type="button" className="btn btn-sm btn-primary" style={{ "marginRight": "10px" }} onClick={this._back}>返回</button>
                </div>
            )
        }
    };

    _back = () => {
        this.context.router.history.goBack();
    };

    _calc = () => {
        let { investmentData } = this.state,
            { rate, investNum,period} = investmentData;
        let expectedReturn = parseFloat(rate, 10) * investNum * period/12/ 100;
        if (!isNaN(expectedReturn)) {
            investmentData.expectedReturn = expectedReturn.toFixed(2);
            this.setState({ investmentData });
        }
    };

    _dataHandler = (dataItem) => {
        return { name: dataItem.carNo, value: dataItem.id };
    };

    /**
     * 刷新
     */
    _refresh = () => {
        if (this.id) {
            Get(`/spi/custInvest/view/${this.id}`)
                .then((investmentData) => {
                    investmentData.custPhone = investmentData.phone;
                    investmentData.beginDate = Moment(investmentData.calRateBeginDate).format('YYYY-MM-DD');
                    investmentData.endDate = Moment(investmentData.calRateEndDate).format('YYYY-MM-DD');
                    if (investmentData.car && investmentData.car.id) {
                        car = investmentData.car.id;
                    }
                    if (investmentData.productId && investmentData.productId.id) {
                        productId = investmentData.productId.id;
                    }
                    this.setState({ investmentData });
                });
        } else {
            this.setState({ investmentData: {} });
        }
    };

    /**
     * 保存
     */
    _save = () => {
        let { investmentData } = this.state;
        investmentData.beginDate = investmentData.beginDate || startDate;
        investmentData.endDate = investmentData.endDate || endDate;

        if (investmentData.beginDate) {
            let a = Moment(investmentData.beginDate, "YYYY-MM-DD");
            investmentData.beginDate = a.toDate().getTime();
        }
        if (investmentData.endDate) {
            let b = Moment(investmentData.endDate, "YYYY-MM-DD");
            investmentData.endDate = b.toDate().getTime();
        }
        if (investmentData.productId) {
            investmentData.productId = investmentData.productId.id || null;
        }
        if (investmentData.car) {
            investmentData.car = investmentData.car.id || null;
        }
        investmentData.productId = productId;
        investmentData.car = car;
        Post('/spi/custInvest/edit', investmentData)
            .then((r) => {
                Dialog.alert(investmentData.id ? '更新成功' : '新增成功', () => {
                    this.context.router.history.goBack();
                });
            });
    };

    /**
     * 审核
     */
    _audit = (status) => {
        PostString(`/spi/custInvest/audit?id=${this.id}&type=${status}`)
            .then(() => {
                Dialog.alert('提交成功', () => {
                    this.context.router.history.goBack();
                });
            });
    };
}

export default InvestmentEdit;